#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Desc : 查询中小学教师资格考试(NTCE)成绩
# @Time : 19.12.11 16:41 
# @Author : By Joker
# @File : query_mark
# @Software: PyCharm
import os
import time

import requests

from src.cjcx_neea.fateadm_api import FateadmApi
from src.utils.user_agent import UserAgent

resultPath = "/src/static/result/"  # 成绩结果存放路径
result404Path = "/src/static/result/404/"  # 请求错误结果存放路径
verifyImageUrl = "http://search.neea.edu.cn/Imgs.do"  # 验证码请求地址
queryMarkUrl = "http://search.neea.edu.cn/QueryMarkUpAction.do"  # 分数查询请求地址


class QueryMark:
    global count
    count = 0

    global headers
    headers = {
        "Accept": "image/webp,image/apng,image/*,*/*;q=0.8",
        "Referer": "http://search.neea.edu.cn/QueryMarkUpAction.do?act=doQueryCond&pram=results&community=Home"
                   "&sid=2nasVMoohJ6cFnsQEIjGYmh",
        "DNT": "1",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "zh-CN",
        "User-Agent": UserAgent.randomUserAgent(),
    }

    def __init__(self, name, id_card):
        self.name = name
        self.id_card = id_card

    def reqVerifyImage(self):
        """
        请求验证码图片
        :return: 图片内容
        """
        global headers
        params = {
            "act": "verify",
            "t": time.time(),
        }
        resp = requests.get(url=verifyImageUrl, params=params, headers=headers)
        # 若请求错误，则重新请求三次
        if resp.status_code != 200:
            global count
            count += 1
            if count == 4:
                print("请求地址或参数有误！")
                return
            # 休眠15s，以免连续请求
            time.sleep(15)
            self.reqVerifyImage()

        # 保存cookie
        ck = ""
        for k, v in resp.cookies.get_dict().items():
            ck += "{}={};".format(k, v)
        headers.update({"Cookie": ck})

        return resp.content

    def getImageResultContent(self):
        """
        识别图片验证码内容
        :return: 结果
        """
        # pd账号秘钥，请在用户中心页获取
        pd_id = "90098"
        pd_key = "098098"
        app_id = "88"
        app_key = "88+aqJbCProjHcGofDu"
        pred_type = "30400"
        api = FateadmApi(app_id, app_key, pd_id, pd_key)

        # 查询余额
        balance = api.QueryBalcExtend()
        if balance <= 0:
            print("余额不足，请及时充值！")
            return "403"

        # 返回识别结果
        print("{}-{}: 正在查询！".format(self.name, self.id_card))
        rsp = api.Predict(pred_type, self.reqVerifyImage())

        if rsp.ret_code != 0:
            print("获取识别结果失败：" + rsp.err_msg)
            return "403"

        return rsp.pred_rsp.value

    def queryNtceResults(self):
        """
        查询 NTCE 成绩
        :return:
        """
        verify = self.getImageResultContent()
        if verify == '403':
            return

        params = {
            "act": "doQueryNtceResultsList",
            "pram": "results",
            "ksxm": "2nasVMoohJ6cFnsQEIjGYmh",
            "nexturl": "%2FQueryMarkUpAction.do%3Fact%3DdoQueryCond%26sid%3D2nasVMoohJ6cFnsQEIjGYmh%26pram%3Dresults"
                       "%26zjhm%3D456%26xm%3D%E7%BD%97%E6%AC%A3",
            "xm": self.name,
            "zjhm": self.id_card,
            "verify": verify,
        }

        hd = {"Content-Type": "application/x-www-form-urlencoded"}
        global headers
        headers.update(hd)
        result = requests.post(url=queryMarkUrl, params=params, headers=headers)

        # 将结果写入文件
        if self.id_card not in result.text or "报告分满分120分，70分及以上为合格" not in result.text:
            print("{}-{}: 查询结果为空！".format(self.name, self.id_card))
            if "您查询的结果为空，请按以下步骤再次确认" not in result.text:
                file_name = "{}-{}查询错误，验证码- {}.html".format(self.name, self.id_card, verify)
                file_path = os.path.abspath("../../") + result404Path + file_name
                with open(file_path, 'a') as re:
                    html = result.text.replace("charset=utf-8", "charset=gb2312")  # 解决中文乱码
                    re.write(html)
            return

        file_name = "{}-{}.html".format(self.name, self.id_card)
        file_path = os.path.abspath("../../") + resultPath + file_name
        with open(file_path, 'a') as re:
            html = result.text.replace("charset=utf-8", "charset=gb2312")  # 解决中文乱码
            re.write(html)
            print('{} 保存成功，保存路径：{}'.format(file_name, file_path))

    @staticmethod
    def generateQueryInformation():
        cards = []
        for i in range(0, 10):
            for j in range(0, 10):
                cards.append("43407115670714{}{}67".format(i, j))
        return cards


if __name__ == '__main__':
    qm = QueryMark("", "")
    info = qm.generateQueryInformation()
    for v in info:
        qm.__init__("李", v)
        time.sleep(5)
        qm.queryNtceResults()
